//
// Created by 1065246 on 2023/11/6.
//
#include <stdio.h>
#include <string.h>


int write1() {
    FILE *fp = fopen("./hello.txt", "w");
    if (fp == NULL) {
        printf("open file failed");
        return 1;
    }

    char *buf = "i am zhouyu";
    size_t lenth = strlen(buf);
    for (int i = 0; i < lenth; ++i) {
        int ch = fputc(buf[i], fp);
        printf("%c", ch);
    }
    printf("\n");
    fclose(fp);
    return 1;
}

int read1() {

    //打开文件
    FILE *fp = fopen("./hello.txt", "r");
    if (fp == NULL) {
        printf("open file failed");
        return 1;
    }

    //逐个字符读取
    char ch;
    while (ch = fgetc(fp)) {
        if (feof(fp)) {
            printf("\nReached end of file.\n");
            break;
        }
        printf("%c", ch);
    }
    printf("\n");
    fclose(fp);
    return 0;
}

int write2() {
    FILE *fp = fopen("hello2.txt", "w");
    if (fp == NULL) {
        printf("open failed");
        return 0;
    }
    char *string = "Hello, world!";
    if (fputs(string, fp) == EOF) {
        printf("write failed");
        return 0;
    }
    fclose(fp);
    return 0;
}

int read2() {
    FILE *fp = fopen("hello2.txt", "r");
    if (fp == NULL) {
        printf("open failed");
        return 0;
    }
    char line[20];
    fgets(line, 3, fp);
    printf("%s", line);
    fclose(fp);
    return 0;
}

struct Person {
    char name[20];
    int age;
    double height;
};

int write3() {
    FILE *fp = fopen("example.bin", "wb");
    if (fp == NULL) {
        printf("open failed");
    }
    struct Person person;
    person.age = 30;
    person.height = 165.88;
    strncpy(person.name, "zhouyu", sizeof(person.name));
    if (fwrite(&person, sizeof(person), 1, fp) != 1) {
        printf("write file failed");
        return 1;
    }
    fclose(fp);
    return 0;
}

int read3() {
    FILE *fp = fopen("example.bin", "rb");
    if (fp == NULL) {
        printf("read failed");
    }
    struct Person person;
    if (fread(&person, sizeof(person), 1, fp) != 1) {
        printf("read to person failed");
        return 1;
    }
    printf("name:%s\n", person.name);
    printf("age:%ud\n", person.age);
    printf("age:%f\n", person.height);
    fclose(fp);
    return 0;
}

int main() {
    // write1();
    // read1();
    // write2();
    // read2();

//    write3();
    read3();
}
